import {Button, Col, Form, Input, message, Modal, Pagination, Row, Select, Space, Table, Tag, Card, Typography} from "antd";
import { PlusOutlined, SearchOutlined, ReloadOutlined } from "@ant-design/icons";
import 'antd/dist/antd.css';
import {useEffect, useState} from "react";
import request from "umi-request";
const { Title } = Typography;

interface Task {
    Id: number;
    TaskName: string;
    TaskLabel: string;
    ExecutorId: number;
    ExecutorName: string;
    Strategy: string;
    Cron: string;
    Status: number;
    TaskParam: string;
}

interface Response {
    Total: number;
    Data: Task[];
    Error: string;
}

interface Executor {
    Id: number;
    Name: string;
}

const TasksPage = () => {
    const columns = [
        {
            title: "序号",
            dataIndex: "Id",
            key: "Id",
        },
        {
            title: "任务名称",
            dataIndex: "TaskName",
            key: "TaskName",
        },
        {
            title: "任务标识",
            dataIndex: "TaskLabel",
            key: "TaskLabel",
        },
        {
            title: "执行器名称",
            dataIndex: "ExecutorName",
            key: "ExecutorName",
        },
        {
            title: "执行策略",
            dataIndex: "Strategy",
            key: "Strategy",
            render: (status: string) => {
                if (status == "1") {
                    return <Tag color="#108ee9">第一个(默认)</Tag>;
                } else {
                    return <Tag>未知</Tag>;
                }
            },
        },
        {
            title: "Cron表达式",
            dataIndex: "Cron",
            key: "Cron",
        },
        {
            title: "任务状态",
            dataIndex: "Status",
            key: "Status",
            render: (status: number) => {
                if (status == 1) {
                    return <Tag color="#87d068">Running</Tag>;
                } else {
                    return <Tag>Stop</Tag>;
                }
            },
        },
        {
            title: "任务参数",
            dataIndex: "TaskParam",
            key: "TaskParam",
        },
        {
            title: "操作",
            key: "action",
            render: (_: any, record: any) => (
                <Space size="middle">
                    <Button
                        type="primary"
                        onClick={(e) => {
                            updateButtonClickHandler(record);
                        }}
                    >
                        编辑
                    </Button>
                    <Button
                        type="primary"
                        onClick={(e) => {
                            runOnceButtonClickHandler(record.Id);
                        }}
                    >
                        执行一次
                    </Button>
                    <Button
                        type="primary"
                        onClick={(e) => {
                            deleteButtonClickHandler(record.Id);
                        }}
                    >
                        删除
                    </Button>
                </Space>
            ),
        },
    ];

    const {Option} = Select;

    const [isModalVisible, setIsModalVisible] = useState(false);
    const [modalTitle, setModalTitle] = useState("新增任务");

    const updateButtonClickHandler = (record: any) => {
        setIsModalVisible(true);
        queryExecutors();
        setModalTitle("编辑任务");
        // todo 后面要换成从后台取最新的记录 不能直接从列表里面获取，以防别人修改过
        form.setFieldsValue(record);
    };

    const runOnceButtonClickHandler = (id: number) => {
        taskForm.setFieldsValue({Id: id});
        setTaskModalVisible(true);
    };

    const deleteButtonClickHandler = (id: number) => {
        request
            .post("/api/task/delete", {
                data: {Id: id},
            })
            .then((res) => {
                message.success(res);
                queryData();
            })
            .catch((error) => {
                message.error("请求数据错误！").then((r) => {
                    console.log(r);
                });
            });
    };

    let inputValue = "";

    const [tasks, setTasks] = useState<Task[]>([]);

    const [executors, setExecutors] = useState<Executor[]>([]);

    const [name, setName] = useState<string>("");

    const [pageNo, setPageNo] = useState<number>(1);

    const [pageSize, setPageSize] = useState<number>(10);

    const [total, setTotal] = useState<number>(0);

    const [taskModalVisible, setTaskModalVisible] = useState(false);

    const pageChangeHandler = (n: number, size: number) => {
        setPageNo(n);
        setPageSize(size);
    };

    const queryExecutors = () => {
        request
            .post("/api/executor/select")
            .then((res) => {
                setExecutors(res.Data);
            })
            .catch((error) => {
                message.error("请求数据错误！").then((r) => {
                    console.log(r);
                });
            });
    };

    const runOnce = (values: any) => {
        request
            .post("/api/task/runOnce", {
                data: values,
            })
            .then((res) => {
                message.success(res);
            })
            .catch((error) => {
                message.error("执行一次请求失败！").then((r) => {
                    console.log(error);
                });
            });
    };

    const queryData = () => {
        request
            .post("/api/task/list", {
                data: {taskName: name, pageNo: pageNo, pageSize: pageSize},
            })
            .then((res) => {
                setTasks(res.Data);
                setTotal(res.Total);
            })
            .catch((error) => {
                message.error("请求数据错误！").then((r) => {
                    console.log(error);
                });
            });
    };

    const onFinish = (values: any) => {
        const {Id} = values;
        if (Id) {
            // 更新任务
            request
                .post("/api/task/update", {
                    data: values,
                })
                .then((res) => {
                    message.success(res);
                    queryData();
                })
                .catch((error) => {
                    message.error("更新任务出错！").then((r) => {
                        console.log(error);
                    });
                });
        } else {
            // 新建任务
            request
                .post("/api/task/add", {
                    data: values,
                })
                .then((res) => {
                    message.success(res);
                    queryData();
                })
                .catch((error) => {
                    message.error("新建任务出错！").then((r) => {
                        console.log(error);
                    });
                });
        }
    };

    const onTaskFinish = (values: any) => {
        runOnce(values);
    };

    const handleOk = () => {
        form.submit();
        setIsModalVisible(false);
    };

    const handleCancel = () => {
        setIsModalVisible(false);
        form.resetFields();
    };

    const handleTaskOk = () => {
        taskForm.submit();
        setTaskModalVisible(false);
    };

    const handleTaskCancel = () => {
        setTaskModalVisible(false);
        taskForm.resetFields();
    };

    const layout = {
        labelCol: {span: 8},
        wrapperCol: {span: 16},
    };

    const onExecutorChange = (value: any, option: any) => {
        if (!value) {
            return;
        }
        form.setFieldsValue({ExecutorName: option.Name});
    };

    const [form] = Form.useForm();
    const [taskForm] = Form.useForm();

    useEffect(() => {
        queryData();
    }, [name, pageNo, pageSize]);
    return (
        <div>
            <Card 
                title={<Title level={4}>任务管理</Title>}
                extra={<Button 
                    type="primary" 
                    icon={<PlusOutlined/>}
                    onClick={() => {
                        setIsModalVisible(true);
                        queryExecutors();
                        setModalTitle("新增任务");
                        form.resetFields();
                    }}
                >
                    新增任务
                </Button>}
                style={{ marginBottom: '24px', borderRadius: '8px' }}
            >
                <Form layout="inline" style={{ marginBottom: '24px' }}>
                    <Form.Item>
                        <Input
                            placeholder="请输入任务名称"
                            allowClear
                            style={{ width: '240px' }}
                            onChange={(e) => {
                                inputValue = e.target.value;
                            }}
                        />
                    </Form.Item>
                    <Form.Item>
                        <Button
                            type="primary"
                            icon={<SearchOutlined/>}
                            onClick={() => {
                                setName(inputValue);
                                setPageNo(1);
                            }}
                        >
                            搜索
                        </Button>
                    </Form.Item>
                    <Form.Item>
                        <Button
                            icon={<ReloadOutlined/>}
                            onClick={() => {
                                setName("");
                                setPageNo(1);
                                queryData();
                            }}
                        >
                            重置
                        </Button>
                    </Form.Item>
                </Form>
                
                <Table 
                    columns={columns} 
                    dataSource={tasks} 
                    pagination={false}
                    rowKey="Id"
                    bordered
                    size="middle"
                    style={{ marginBottom: '16px' }}
                />
                
                <Pagination
                    total={total}
                    current={pageNo}
                    pageSize={pageSize}
                    onChange={pageChangeHandler}
                    showSizeChanger
                    showQuickJumper
                    showTotal={(total) => `共 ${total} 条记录`}
                    style={{ textAlign: 'right' }}
                />
            </Card>
            <Modal
                title={modalTitle}
                visible={isModalVisible}
                onOk={handleOk}
                onCancel={handleCancel}
                okText={"确认提交"}
                cancelText={"取消"}
            >
                <Form {...layout} form={form} name="control-hooks" onFinish={onFinish}>
                    <Form.Item name="Id" label="唯一标识" hidden>
                        <Input/>
                    </Form.Item>
                    <Form.Item
                        name="TaskName"
                        label="任务名称"
                        rules={[{required: true}]}
                    >
                        <Input/>
                    </Form.Item>
                    <Form.Item
                        name="TaskLabel"
                        label="任务标识"
                        rules={[{required: true}]}
                    >
                        <Input/>
                    </Form.Item>
                    <Form.Item
                        name="ExecutorId"
                        label="执行器名称"
                        rules={[{required: true}]}
                    >
                        <Select
                            placeholder="请选择执行器名称"
                            allowClear
                            options={executors}
                            fieldNames={{
                                label: "Name",
                                value: "Id",
                            }}
                            onChange={onExecutorChange}
                        ></Select>
                    </Form.Item>
                    <Form.Item name="ExecutorName" label="执行器名称" hidden>
                        <Input/>
                    </Form.Item>
                    <Form.Item
                        name="Strategy"
                        label="执行策略"
                        rules={[{required: true}]}
                    >
                        <Select placeholder="请选择执行器选择策略" allowClear>
                            <Option value="1">第一个</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="Cron"
                        label="Cron表达式"
                        rules={[{required: true}]}
                    >
                        <Input/>
                    </Form.Item>
                    <Form.Item
                        name="Status"
                        label="任务状态"
                        rules={[{required: true}]}
                    >
                        <Select placeholder="请选择任务状态" allowClear>
                            <Option value={0}>停止</Option>
                            <Option value={1}>开启</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item name="TaskParam" label="任务参数">
                        <Input/>
                    </Form.Item>
                </Form>
            </Modal>
            <Modal
                title={"执行任务"}
                visible={taskModalVisible}
                onOk={handleTaskOk}
                onCancel={handleTaskCancel}
                okText={"确认提交"}
                cancelText={"取消"}
            >
                <Form
                    {...layout}
                    form={taskForm}
                    name="control-hooks"
                    onFinish={onTaskFinish}
                >
                    <Form.Item name="Id" label="唯一标识" hidden>
                        <Input/>
                    </Form.Item>
                    <Form.Item name="TaskParam" label="任务参数">
                        <Input/>
                    </Form.Item>
                    <Form.Item name="ExecutorAddress" label="执行器地址">
                        <Input/>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default TasksPage;
